package com.news.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.news.common.CommonEnum;
import com.news.common.ResponseBean;
import com.news.common.ResultUtil;
import com.news.common.ToolsUtils;
import com.news.entity.CheckNews;
import com.news.entity.NewsCategory;
import com.news.entity.SysNews;
import com.news.service.CheckNewsService;
import com.news.service.NewsCategoryService;
import com.news.service.SysNewsService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @auther gxcc
 * @create 2021/3/26 14:59
 */
@Controller
@RequestMapping("/check")
public class CheckController {
    private static  final Logger logger= LoggerFactory.getLogger(CheckController.class);
    @Autowired
    CheckNewsService checkNewsService;
    @Autowired
    SysNewsService newsService;
    @Autowired
    NewsCategoryService newsCategoryService;

//    private
//    用于返回查询页面
    @RequestMapping("/checklist")
    public String checklist(){
        return "checknews/checklist";
    }
    /**
     * 新闻审核列表查询
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param queryParam 查询参数
     * @param vagueParam 模糊参数
     * @return
     */
    @ApiOperation("获取新闻审核列表")
    @RequestMapping("/list/{pageNum}/{pageSize}")
    @ResponseBody
    public ResponseBean getList(@PathVariable Integer pageNum, @PathVariable Integer pageSize, CheckNews queryParam, String vagueParam) {
        logger.debug("查询新闻列表参数："+queryParam+",pageNum:"+pageNum+",pageSize:"+pageSize);
        QueryWrapper<CheckNews> queryWrapper=new QueryWrapper<>();
        Long categoryId = queryParam.getCategoryId();
        queryWrapper.eq(categoryId!=null,"category_id",categoryId);
        String title = queryParam.getTitle();
        queryWrapper.like(!StringUtils.isEmpty(title),"title",title);
        if(!StringUtils.isEmpty(vagueParam)){
            // and ( title like '%XXXX%' or theme like '%YYYY%')
            queryWrapper.and(
                    e->e.like("title",vagueParam)
                            .or()
                            .like("theme",vagueParam)
            );
        }
        queryWrapper.orderByDesc("id");

        IPage<CheckNews> indexPage = new Page<>(pageNum, pageSize);

        IPage<CheckNews> newsIPage = checkNewsService.page(indexPage, queryWrapper);
        logger.debug("获取的新闻列表："+newsIPage);
        Map resultMap = ToolsUtils.wrapperResult(newsIPage, "newsList");
        return ResultUtil.successData(resultMap);
    }
    /**
     * 新闻审核管理
     * @param news
     * @return
     */
    @RequestMapping("/check")
    @ResponseBody
    public ResponseBean updateById(CheckNews news, HttpSession session) {
        if (news == null||news.getId()==null) {
            return ResultUtil.error(CommonEnum.BAD_PARAM);
        }
        Long categoryId = news.getCategoryId();
        news.setCategoryName(newsCategoryService.getById(categoryId)==null?"":newsCategoryService.getById(categoryId).getName());
        news.setUserId(ToolsUtils.getLoginUserId(session));
        news.setUserName(ToolsUtils.getLoginUserName(session));
        news.setUpdateTime(LocalDateTime.now());
        boolean i = checkNewsService.updateById(news);
        return ResultUtil.successData(news);
    }
    /**
     * 跳转到新闻审核页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/checkedit/{id}")
    public String editPage(@PathVariable Long id, Model model) {
        model.addAttribute("checknews", checkNewsService.getById(id));
        return "checknews/checkedit";
    }

    @ModelAttribute
    public void addModelAttribute(Model model){
        List<NewsCategory> categoryList = newsCategoryService.list();
        model.addAttribute("categoryList",categoryList);
    }
//    审核通过之后上传真正的数据库
    @RequestMapping("add")
    @ResponseBody
    public ResponseBean addNews(SysNews news, HttpSession session){
        logger.debug("addSysNews:"+news);
        news.setUserId(ToolsUtils.getLoginUserId(session));
        news.setUserName(ToolsUtils.getLoginUserName(session));
        Long categoryId = news.getCategoryId();
        news.setCategoryName(newsCategoryService.getById(categoryId)==null?"":newsCategoryService.getById(categoryId).getName());
//        审核之后进行删除
        checkNewsService.removeById(news.getId());
        boolean i = newsService.save(news);
        logger.debug("保存后的news:"+news);
        return ResultUtil.successData(news);
    }

    @RequestMapping("deleteById")
    @ResponseBody
    public ResponseBean deleteById(@RequestParam Long id){
        if(id==null||id<0){
            return ResultUtil.error(CommonEnum.BAD_PARAM);
        }
        boolean delete = checkNewsService.removeById(id);
        return ResultUtil.success() ;
    }
}
